package Cau2;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TCPServer {
	ServerSocket ss;
	Socket cnnSocket;

	public TCPServer() {
		try {
			ss = new ServerSocket(1234);
			System.out.println("Server dang chay...");
		} catch (IOException e) {

			e.printStackTrace();
		}

	}

	public void run() throws IOException {

		String strClient;
		String strServer;
		String fileName = "log.txt";

		while (true) {
			cnnSocket = ss.accept();
			BufferedReader inFromclient = new BufferedReader(
					new InputStreamReader(cnnSocket.getInputStream()));
			DataOutputStream outToclient = new DataOutputStream(
					cnnSocket.getOutputStream());
			strClient = inFromclient.readLine();
			if (strClient.contains("+DUNGSERVER")) {
				String strSv = "Khong the ket noi toi server";
				outToclient.writeBytes(strSv);
				break;
			}

			Date timeNow = new Date(System.currentTimeMillis());
			SimpleDateFormat sdt = new SimpleDateFormat("dd-MM-yyy--hh:mm:ss:a");
			String strTime = sdt.format(timeNow);
			FileOutputStream fos = new FileOutputStream(fileName, true);
			PrintWriter pw = new PrintWriter(fos);

			pw.write(cnnSocket.getInetAddress().getHostName() + " ["
					+ cnnSocket.getInetAddress().getHostAddress() + "] " + " ["
					+ strTime + "] " + " [" + getFistWord(strClient) + "v "
					+ getLastWord(strClient) + "mA ] \r\n");
			pw.close();
			
			
			
			strServer = "Da luu lai du lieu thanh cong"+'\n';
			outToclient.writeBytes(strServer);
		}
		System.out.println("Server ket thuc.....");
		cnnSocket.close();
		ss.close();

	}

	String getFistWord(String data) throws IOException {
		data.trim();
		return data.substring(0, data.indexOf(' '));
	}

	String getLastWord(String data) throws IOException {
		data.trim();
		return data.substring(data.indexOf(' ') + 1);
	}

	public static void main(String[] args) throws IOException {
		TCPServer server = new TCPServer();
		server.run();
	}



}
